package ee.ut.sysmodel.bgmn.model;

public class Pin {
	
	private int pieceCount;
	protected Player pieceOwner;
	private int number;
	
	public Pin(int number) {
		this.number = number;
		
		pieceCount = 0;
		pieceOwner = null;
	}
	
	public int getNumber() {
		return number;
	}
	
	public int getPieceCount() {
		return pieceCount;
	}
	
	public boolean isOwned() {
		return pieceOwner != null;
	}
	
	public Player getOwner() {
		return pieceOwner;
	}
	
	// XXX: Made public temporarily to test stuff
	public void setState(Player owner, int amount) { // "public" omitted purposefully - this must not be used outside the package
		pieceOwner = owner;
		this.pieceCount = amount;
	}
	
	void removePiece() throws BackgammonException {
		if(pieceCount == 0)
			throw new BackgammonException("Can't remove piece from an empty pin");
		
		pieceCount--;
		
		if(pieceCount == 0)
			pieceOwner = null;
	}
	
	// true, if a piece was eaten
	boolean addPiece(Player owner) throws BackgammonException {
		if(!isOwned()) {
			pieceOwner = owner;
			pieceCount = 1;
			return false;
		}
		
		if(owner == pieceOwner) {
			pieceCount++;
			return false;
		}
		
		if(pieceCount > 1){
			throw new BackgammonException("Can't place a checker onto pin, where there are more than 1 of opposite color checkers");
		}
		
		pieceOwner = owner;
		return true;
	}
}
